import NProgress from 'nprogress'; // progress bar
import 'nprogress/nprogress.css'; // progress bar style

import store from '@/store';
import router from '@/router';
import { MessagePlugin as Message,DialogPlugin } from 'tdesign-vue';
import { getToken } from '@/utils/auth'



NProgress.configure({showSpinner: false});

const whiteListRouters = ['/login', '/auth-redirect', '/bind', '/register','/expert-invite','/expert-detail', '/bzhEvaluation']

router.beforeEach(async (to, from, next) => {
  // 设置来源path
  localStorage.setItem("historyPath", from.path)
  NProgress.start();
  if (getToken()) {
    if (to.path === '/login') {
      next()
    } else if (store.state.user.roles.length === 0) {
      // 判断当前用户是否已拉取完user_info信息
      store.dispatch('user/GetInfo').then(() => {
        store.dispatch('permission/initRoutes', {
          permissions:store.state.user.permissions, services:store.state.user.services
        }).then(() =>{
          next({...to, replace: true});
          // 中断当前导航，执行新的导航 replace: true只是一个设置信息，告诉VUE本次操作后，不能通过浏览器后退按钮，返回前一个路由。
          // 其实next({ ...to })的执行很简单，它会判断：
          // 如果参数to不能找到对应的路由的话，就再执行一次beforeEach((to, from, next)直到其中的next({ ...to})能找到对应的路由为止。
        });
      }).catch(err => {
        // Message.error(err.toString());
        next(`/login?redirect=${to.path}`)
        NProgress.done();
      })
    } else {
      next()
    }
  } else {
    /* white list router */
    if (whiteListRouters.indexOf(to.path) !== -1) {
      next();
    } else {
      next(`/login?redirect=${to.path}`);
    }
    NProgress.done();
  }
});

router.onError((error, to) => {
  if (error.message.includes('Failed to fetch dynamically imported module')) {
    const confirmDia = DialogPlugin.confirm({
      header: "系统提示",
      body: `检测到系统有更新是否刷新页面`,
      theme: "warning",
      onConfirm: ({e}) => {
        window.location.reload();
        confirmDia.destroy();
      },
    })
  }
})

router.afterEach((to, from, next) => {
  document.title = to?.meta?.title || document.title;
  NProgress.done();
});
